<template>
  <div class="user">
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input placeholder="请输入查询名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            :disabled="keyword ? false : true"
          >
            查询
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="primary" @click="addUser" v-has="`btn.User.add`">
        添加用户
      </el-button>
      <el-button
        type="danger"
        :disabled="selectIdArr.length ? false : true"
        @click="delSelectUser"
      >
        批量删除
      </el-button>
      <el-table
        @selection-change="selectChange"
        :data="userArr"
        border
        style="margin-top: 10px"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名字"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="用户名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="roloName"
          label="用户角色"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确定要删除${row.username}?`"
              width="260px"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        :small="small"
        :pager-count="9"
        @size-change="getHasUser"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-drawer v-model="drawer" direction="rtl" size="30%">
      <template #header>
        <h4>{{ userParams.id ? '编辑用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请输入密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer1" direction="rtl" size="30%">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true"></el-input>
          </el-form-item>
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
              :value="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form>
      </template>
      <template #footer>
        <el-button type="default" @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting.ts'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetRole,
  reqDeleteUser,
  reqSelectUser,
} from '@/api/acl/user'
import {
  UserResponseData,
  Records,
  User,
  RoleResponseData,
  AllRole,
  SetRoleData,
} from '@/api/acl/user/type'
const useSettingStore = useLayOutSettingStore()
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const total = ref<number>()
let userArr = ref<Records>([])
// 存储全部的职位信息
let allRole = ref<AllRole>([])
// 存储用户职位信息
let userRole = ref<AllRole>([])
// 角色分配
const drawer = ref(false)
// 编辑角色
const drawer1 = ref(false)
const formRef = ref<any>()
const selectIdArr = ref<User[]>([])
const userParams = reactive<User>({
  username: '',
  password: '',
  name: '',
})
const keyword = ref<string>('')
const getHasUser = async (page = 1) => {
  currentPage.value = page
  let result: UserResponseData = await reqUserInfo(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    userArr.value = result.data.records
    total.value = result.data.total
  }
}
onMounted(() => {
  getHasUser()
})

const handleCurrentChange = (value: number) => {
  getHasUser(value)
}
const setRole = async (row: any) => {
  Object.assign(userParams, row)
  let result: RoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
    drawer1.value = true
  }
  console.log(userRole.value)
  console.log(allRole.value)
}
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    username: '',
    password: '',
    name: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
const updateUser = (row: any) => {
  drawer.value = true
  Object.assign(userParams, row)
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
const deleteUser = async (id: number) => {
  console.log(id)
  let result: any = await reqDeleteUser(id)
  if (result.code == 200) {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getHasUser(currentPage.value)
  } else {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }
}
// 这是添加用户的处理回调
const save = async () => {
  // 发请求前要先校验成功才行
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      message: userParams.id ? '更新成功' : '添加成功',
      type: 'success',
    })
    getHasUser(userParams.id ? currentPage.value : 1)
    window.location.reload()
  } else {
    ElMessage({
      message: userParams.id ? '更新失败' : '添加失败',
      type: 'error',
    })
  }
}
// 这是取消
const cancel = () => {
  drawer.value = false
}
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户姓名不能小于5位'))
  }
}
const validatorname = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称不能小于5位'))
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('用户密码不能小于6位'))
  }
}
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const handleCheckAllChange = (val: boolean) => {
  // val是全不选和全选
  userRole.value = val ? allRole.value : []
  // 是不确定
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  checkAll.value = value.length === allRole.value.length
  isIndeterminate.value = value.length !== allRole.value.length
}
const confirmClick = async () => {
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => {
      return item.id as number
    }),
  }
  let result: any = await reqSetRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配职位成功',
    })
    drawer1.value = false
    getHasUser(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配职位失败',
    })
  }
}
const selectChange = (value: any) => {
  selectIdArr.value = value
  console.log(value)
}
const delSelectUser = async () => {
  let idList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  console.log(idList)

  let result: any = await reqSelectUser(idList)
  console.log(result)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(
      userArr.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const search = () => {
  getHasUser()
  keyword.value = ''
}
const reset = () => {
  useSettingStore.refresh = !useSettingStore.refresh
}
</script>
<style lang="scss">
.user {
  .el-card {
    margin-top: 10px;
  }
}
.user {
  .form {
    display: flex;
    justify-content: space-between;
  }
}
</style>
